package com.supreme.nettyapp.generalserver.socketserver.service;

import com.supreme.nettyapp.generalserver.service.NettyServerService;
import com.supreme.nettyapp.generalserver.socketserver.handler.SocketServerInitializer;
import com.supreme.nettyapp.generalserver.socketserver.props.SocketServerProps;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SocketServerService implements NettyServerService, DisposableBean {

    @Resource
    private SocketServerProps socketServerProps;

    private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;

    @Async(value = "nettyTask")
    @Override
    public void startNettyServer() {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(SocketServerInitializer.INSTANCE);

            Integer serverPort = socketServerProps.getPort();
            ChannelFuture channelFuture = serverBootstrap.bind(serverPort).sync();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("Netty server started on port " + serverPort);
                } else {
                    System.err.println("Failed to start Netty server: " + future.cause());
                }
            });

            channel = channelFuture.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroyNettyServer() {

    }

    @Override
    public void destroy() throws Exception {
        if (channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        System.out.println("Netty server resources released");
    }
}
